import datetime

from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info import user_login_data
from info.models import User, News
from info.response_code import RET
from . import admin_blu


@admin_blu.route("/login", methods=["GET", "POST"])
def admin_login():
    """管理员登陆页面[作业]"""
    if request.method == "GET":
        return render_template("admin/login.html")

    # 登陆成功
    # session["is_admin"] = True  # 登陆成功以后
    # session["user_id"] = user.id  # 管理员的ID
    else:
        """接收登陆信息"""
        data_dict = request.form
        mobile = data_dict.get("mobile")
        password = data_dict.get("password")

    if not all([mobile, password]):
        return render_template('admin/login.html', errmsg="参数不足")
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html', errmsg="数据查询失败")

    if not user:
        return render_template('admin/login.html', errmsg="用户不存在")

    if not user.check_passowrd(password):
        return render_template('admin/login.html', errmsg="密码错误")

    if not user.is_admin:
        return render_template('admin/login.html', errmsg="用户权限错误")

    # 登陆成功
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    session["is_admin"] = True

    # 跳转页面
    return redirect(url_for("admin.index"))


@admin_blu.route("/")
@user_login_data
def index():
    """admin后台首页"""
    user = g.user
    # 因为我们已经在请求钩子中设置只有登陆才能访问到后台admin站点，所以我们不需要再次判断了。

    return render_template("admin/index.html", user=user)


@admin_blu.route("/user_count")
@user_login_data
def user_count():
    """用户统计"""
    # 获取总用户数量
    total_count = 0

    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 用户月新增数
    mon_count = 0
    try:
        # 获取当前时间对象
        now = datetime.time.localtime()
        mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        # datetime.strptime 时间格式化
        mon_begin_date = datetime.datetime.strptime(mon_begin, '%Y-%m-%d')
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 用户日新增数
    day_count = 0

    try:
        day_begin = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
        day_begin_date = datetime.datetime.strptime(day_begin, '%Y-%m-%d')
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 输出图标中最近一个月的用户新增数量
    now_date = datetime.datetime.strptime(datetime.datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')
    # 定义空数组，保存数据
    active_date = []
    active_count = []

    # 依次添加数据，再反转
    for i in range(0, 31):
        begin_date = now_date - datetime.timedelta(days=i)
        end_date = now_date - datetime.timedelta(days=(i - 1))
        active_date.append(begin_date.strftime('%Y-%m-%d'))
        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.create_time >= begin_date,
                                      User.create_time < end_date).count()
        except Exception as e:
            current_app.logger.error(e)

        active_count.append(count)

    active_date.reverse()
    active_count.reverse()
    print(active_date)
    print(active_count)

    return render_template("admin/user_count.html",
                           total_count=total_count,
                           mon_count=mon_count,
                           day_count=day_count,
                           active_date=active_date,
                           active_count=active_count
                           )


@admin_blu.route("/news_review")
@user_login_data
def news_review():
    """新闻列表"""
    # 当前页码
    page = int(request.args.get("p", 1))
    # 每一页数据量
    per_page = int(request.args.get("per_page", constants.ADMIN_NEWS_PAGE_MAX_COUNT))

    news_li = []
    # 默认总页码
    total_page = 1

    try:
        paginate = News.query.order_by(News.id.desc()).paginate(page, per_page, False)

        news_li = paginate.items
        page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)

    # 把新闻列表里面的模型对象转成字典
    news_list = []
    for item in news_li:
        news_list.append(item.to_basic_dict())

    return render_template('admin/news_review.html',
                           news_list=news_list,
                           page=page,
                           total_page=total_page,
                           )


@admin_blu.route("/news_review_detail", methods=["POST", "GET"])
@user_login_data
def news_review_detail():
    """新闻审核详情"""

    if request.method == "GET":

        # 获取地址栏的新闻ID
        news_id = int(request.args.get("id", -1))

        if news_id < 1:
            # 如果ID不存在，则返回列表页
            return redirect(url_for("admin.news_review"))

        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        if not news:
            return redirect(url_for("admin.news_review"))

        return render_template("admin/news_review_detail.html", news=news)

    else:
        """POST提交数据"""
        # 接受数据
        data_dict = request.json
        news_id = data_dict.get("news_id")  # 当前正在审核的新闻id
        status = data_dict.get("status")  # 审核的状态
        reason = data_dict.get("reason")  # 拒绝原因

        # 校验数据
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        if not news:
            return jsonify(errmsg="审核新闻不存在")

        # 更新数据
        news.status = status
        if news.status == -1:
            """审核未通过"""
            news.reason = reason

        try:
            db.session.commit()
            # 返回列表页
            return jsonify(errno=RET.OK, errmsg="操作成功")
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DATAERR, errmsg="操作失败")
